<?php

namespace App\Http\Controllers\backend;

use App\Models\Category;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use App\Models\Operation;

class CategoryController extends BaseController {
	
	public function index() {
		$categories = Category::paginate(20);
		return View::make('backend.categories', compact('categories'));
	}
	
	public function create() {
		$category = new Category();
		return view('backend.category_form', compact('category'));
	}
	
	public function store() {
		$input = Input::all();
		$validation = Validator::make($input, Category::$rules, Category::$msgs);
		if($validation->passes()) {
			$category = Category::create($input);
			Operation::create([
				'action' => '添加分类',
				'content' => '添加了分类：' . $category->name,
			]);
			return Redirect::to('/backend/categories');
		}
		
		return Redirect::back()
			->withInput()
			->withErrors($validation);
	}
	
	public function edit($categoryId) {
		$category = Category::find($categoryId);
		return View::make('backend.category_form', compact('category'));
	}
	
	public function destroy($categoryId) {
		$category = Category::find($categoryId);
		if(!is_null($category)) {
			Operation::create([
				'action' => '删除分类',
				'content' => '删除了分类：' . $category->name,
			]);
			$category->delete();
		}
		return Redirect::to('/backend/categories');
	}
	
}
